//
//  wangshiViewController.m
//  xinhua_sx
//
//  Created by love on 14-8-12.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//
#define WRITH  dispatch_queue_create("com.dispatch.writedb", DISPATCH_QUEUE_SERIAL)
#import "wangshiViewController.h"
#import <CommonCrypto/CommonDigest.h>
@interface wangshiViewController ()

@end

@implementation wangshiViewController
@synthesize string = _string;
@synthesize string1 = _string1;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGFloat aY = kIOS_VERSION<7.0?0:20;
    UIView* _navBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0+aY)];
    _navBar.backgroundColor = [UIColor colorWithRed:2.0/255 green:102.0/255 blue:172.0/255 alpha:1.0];
    _navBar.userInteractionEnabled = YES;
    
    UILabel* _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, aY, self.view.frame.size.width, 44)];
    _titleLable.backgroundColor = [UIColor clearColor];
    _titleLable.textColor = [UIColor whiteColor];
    _titleLable.font = [UIFont systemFontOfSize:20];
    _titleLable.textAlignment = NSTextAlignmentCenter;
    _titleLable.text = @"中国网事";
    [_navBar addSubview:_titleLable];
    [self.view addSubview:_navBar];
       UIButton* _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, aY, 40,40.0)];
    [_leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
    
    _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 13, 5, 5);
    [_leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    UIWebView* web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 40+aY, 320, self.view.frame.size.height-60)];
      NSString* sfd = @"http://xhpfm.open.zhongguowangshi.com/open/index" ;
    NSMutableURLRequest* request;
    if ([_string length] > 0)
    {
        sfd = _string;
        _titleLable.text = @"";
        
         sfd = [sfd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sfd]];
       
       
    }
    else if ([_string1 isEqualToString:@"新华社发布"])
    {
         sfd = [sfd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sfd]];
        [request setHTTPMethod: @"POST"];
        
        NSDate *  senddate=[NSDate date];
        
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        
        [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
        
      
        NSInteger seconds = [senddate timeIntervalSince1970];
      
        
        
        int NUMBER_OF_CHARS = 1;
        char data[NUMBER_OF_CHARS];
        for (int x=0;x<NUMBER_OF_CHARS;data[x++] = (char)('a' + (arc4random_uniform(26))));
        
        NSString* gf= [[NSString alloc] initWithBytes:data length:NUMBER_OF_CHARS encoding:NSUTF8StringEncoding];
        
        NSLog(@"fg = %@",gf);
        
        NSString *strRandom = @"";
        
        NSLog(@"0 %i",seconds);
        NSString* fffg = [NSString stringWithFormat:@"%i",seconds];
        for(int i=0; i<5; i++)
        {
            strRandom = [ strRandom stringByAppendingFormat:@"%i",(arc4random() % 9)];
            
        }
        NSString* ff = [NSString stringWithFormat:@"%@%@",gf,strRandom];
        
        NSLog(@"随机数: %@", strRandom);
        NSMutableArray* ar = [[NSMutableArray alloc] initWithArray:@[ff,fffg,APPID,paramKey]];
        
        NSArray *sortedArray = [ar sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            if ([obj1 intValue] > [obj2 intValue]){
                return NSOrderedDescending;
            }
            if ([obj1 intValue] < [obj2 intValue]){
                return NSOrderedAscending;
            }
            return NSOrderedSame;
        }];
        NSLog(@"排序后的数组：%@",sortedArray);
        NSString* skf = [NSString stringWithFormat:@"%@%@%@%@",sortedArray[0],sortedArray[1],sortedArray[2],sortedArray[3]];
        NSLog(@"skf = %@",skf);
        skf = [self sha1:skf];
        NSLog(@"skf sha1 = %@",skf);
        NSString* body = [NSString stringWithFormat:@"paramId=%@&timeStamp=%@&randomNum=%@&myEncrypt=%@",APPID,fffg,ff,skf];
        NSLog(@"body = %@",body);
        [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
       // NSError *err;
       //  NSData *data1=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
       // NSString *str=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
        
       // NSLog(@"\n string:%@\n",str);
        _titleLable.text = @"新华社发布";
    }
    else
     {   sfd = @"http://zgws.xinhuanet.com/api/open/List.aspx?siteid=156&r=0.7723461736459285&wt=中国网事";
         sfd = [sfd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sfd]];
     }
   

    [web loadRequest:request];
    web.delegate = self;
    [self.view addSubview:web];
    // Do any additional setup after loading the view.
}

- (NSString *)sha1:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"start");
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"error = %@",error);
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"finish");
}
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
